package com.xudow.app.dynamicstate_old.module.follow;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.GsonBuilder;
import com.jude.beam.bijection.RequiresPresenter;
import com.jude.beam.expansion.BeamBaseActivity;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.tagview.TAGView;
import com.jude.utils.JUtils;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.domain.entity.AttentionType;
import com.xudow.app.dynamicstate_old.domain.entity.Dynamic;
import com.xudow.app.dynamicstate_old.domain.entity.Grade;
import com.xudow.app.dynamicstate_old.widget.ContainsEmojiEditText;
import com.xudow.app.dynamicstate_old.widget.exview.ImagePieceView;
import com.xudow.app.dynamicstate_old.widget.exview.PieceViewGroup;
import com.xudow.app.ui.widget.LoadingDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by troyl on 2016/4/29.
 * 发布新动态
 */
@RequiresPresenter(NewDynamicPresenter.class)
public class NewDynamicActivity extends BeamBaseActivity<NewDynamicPresenter> {

    private static final String TAG = "NewDynamicActivity";
    // 长文
    private static final int LONGTYPE = 1;
    // 普通
    private static final int NORMALTYPE = 2;

    @BindView(R.id.dynamic_new_short_content)
    ContainsEmojiEditText mEditTextContent;
    //    @BindView(R.id.dynamic_new_short_add_photo)
//    ImageView mImageButtonAddPhoto;
    @BindView(R.id.dynamic_new_short_submit)
    Button mButtonSubmit;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.images)
    PieceViewGroup images;
    @BindView(R.id.share_qq)
    ImageView shareQq;
    @BindView(R.id.share_wechat)
    ImageView shareWechat;
    @BindView(R.id.share_weibo)
    ImageView shareWeibo;
    @BindView(R.id.image_private)
    ImageView imagePrivate;
    @BindView(R.id.text_private)
    TextView textPrivate;
    @BindView(R.id.ll_private)
    LinearLayout llPrivate;
    @BindView(R.id.recycler_grade)
    RecyclerView recyclerViewGrade;

    // 其他界面传来的Intent
    private Intent mIntent;
    boolean isPrivate;

    @OnClick(R.id.dynamic_new_short_submit)
    public void submitDynamic(View view) {
        String content = mEditTextContent.getText().toString();
        if (TextUtils.isEmpty(content.trim()) && getPresenter().getUriArrayList().size() == 0) {
            showShortToast("请填写内容或选择照片");
            return;
        }
        if (lastPos == -1) {
            showShortToast("请选择关注群体");
            return;
        }
        if (lastSelected.getGradeList() != null && lastSelected.getGradeList().size() != 0 && selectGrade.size() == 0) {
            showShortToast("请选择年级");
            return;
        } else {
            lastSelected.setGradeList(selectGrade);
        }
        Dynamic dynamic = new Dynamic();
        dynamic.setContent(content);
        dynamic.setIsprivate(isPrivate ? 1 : 0);
        dynamic.setType(NORMALTYPE);
//        dynamic.setAttentionTypeId(lastSelected.getId());
        dynamic.setUsertype(app.isStudent() ? 2 : 1);
        showLoadingDialog("发送中");
        List<AttentionType> temp = new ArrayList<>();
        temp.add(lastSelected);
        getPresenter().submit(dynamic,
                new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(temp),
                new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(temp));
    }

    @OnClick(R.id.btn_back)
    public void cancel(View view) {
        finish();
    }

    XApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dynamic_activity_new_short);
        ButterKnife.bind(this);
        mIntent = getIntent();

        app = (XApplication) getApplication();
        setupView();
        String[] mPermissionList = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS};
        ActivityCompat.requestPermissions(this, mPermissionList, 100);
    }

    TagAdapter adapter;
    GradeAdapter gradeAdapter;

    private void setupView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerView.setAdapter(adapter = new TagAdapter(this));
//         DynamicModel.getInstance().loadInterest("")
//                .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
//                 .subscribe(list -> {
//                     adapter.clear();
//                     adapter.addAll(list);
//                     adapter.notifyDataSetChanged();
//                 });
        recyclerViewGrade.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerViewGrade.setAdapter(gradeAdapter = new GradeAdapter(this));
        DynamicModel.getInstance().getAttentionTypes()
                .subscribe(attentionTypes -> {
                    adapter.clear();

                    adapter.addAll(attentionTypes);
//                    adapter.notifyDataSetChanged();
                });
        images.setOnAskViewListener(new PieceViewGroup.OnAskViewListener() {
            @Override
            public void onAddView() {
                showSelectorDialog();
            }
        });
        images.setOnViewDeleteListener(getPresenter());
        shareQq.setOnClickListener(v -> {
            if (getPresenter().isShareQQ()) {
                shareQq.setImageResource(R.drawable.share_qq_unfocus);
                getPresenter().setShareQQ(false);
            } else {
                shareQq.setImageResource(R.drawable.share_qq_focus);
                getPresenter().setShareQQ(true);
            }
        });
        shareWechat.setOnClickListener(v -> {
            if (getPresenter().isShareWeChat()) {
                shareWechat.setImageResource(R.drawable.share_wechat_unfocus);
                getPresenter().setShareWeChat(false);
            } else {
                shareWechat.setImageResource(R.drawable.share_wechat_focus);
                getPresenter().setShareWeChat(true);
            }
        });
        shareWeibo.setOnClickListener(v -> {
            if (getPresenter().isShareWeibo()) {
                shareWeibo.setImageResource(R.drawable.share_weibo_unfocus);
                getPresenter().setShareWeibo(false);
            } else {
                shareWeibo.setImageResource(R.drawable.share_weibo_focus);
                getPresenter().setShareWeibo(true);
            }
        });
        llPrivate.setOnClickListener(v -> {
            if (isPrivate) {
                textPrivate.setText("公开");
                textPrivate.setTextColor(getResources().getColor(R.color.text_private));
                imagePrivate.setImageResource(R.drawable.ic_msg_public);
                isPrivate = false;
            } else {
                textPrivate.setText("私密");
                textPrivate.setTextColor(getResources().getColor(R.color.text_color_green));
                imagePrivate.setImageResource(R.drawable.ic_msg_private);
                isPrivate = true;
            }
        });
        selectGrade = new ArrayList<>();
    }

    public void showSelectorDialog() {
        RxPermissions.getInstance(this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(i -> {
                    if (i) {
                        new MaterialDialog.Builder(this)
                                .title("选择图片来源")
                                .items(new String[]{"拍照", "相册"})
                                .itemsCallback(new MaterialDialog.ListCallback() {
                                    @Override
                                    public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                        getPresenter().editFace(which);
                                    }
                                }).show();
                    } else {
                        JUtils.Toast("请授予权限进行操作");
                    }
                });

    }

    public void addImage(Bitmap bitmap) {
        ImagePieceView pieceView = new ImagePieceView(this);
        pieceView.setImageBitmap(bitmap);
        images.addView(pieceView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        ButterKnife.(this);
    }

    class TagAdapter extends RecyclerArrayAdapter<AttentionType> {

        public TagAdapter(Context context) {
            super(context);
        }

        @Override
        public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
            return new TagViewHolder(parent);
        }
    }

    AttentionType lastSelected = new AttentionType();
    int lastPos = -1;

    class TagViewHolder extends BaseViewHolder<AttentionType> {

        @BindView(R.id.tag)
        TextView tag;

        public TagViewHolder(ViewGroup parent) {
            super(parent, R.layout.item_attention_type_new_dynamic);
            ButterKnife.bind(this, itemView);
        }

        @Override
        public void setData(final AttentionType data) {
            if (data == null)
                return;
            tag.setText(data.getName());
            setBackGround(data.isSelected());
            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (lastPos != getAdapterPosition()) {
                        lastSelected.setSelected(false);
                        data.setSelected(true);
                        lastSelected = data;
                        adapter.notifyItemChanged(lastPos);
                        adapter.notifyItemChanged(getAdapterPosition());
                        lastPos = getAdapterPosition();
                        if (data.getGradeList() == null || data.getGradeList().size() == 0) {
                            recyclerViewGrade.setVisibility(View.GONE);
                        } else {
                            recyclerViewGrade.setVisibility(View.VISIBLE);
                            selectGrade.clear();
                            gradeAdapter.clear();
                            gradeAdapter.addAll(data.getGradeList());
//                            gradeAdapter.notifyDataSetChanged();
                        }
                    }
                }
            });
        }

        private void setBackGround(boolean select) {
            if (select) {
                tag.setBackgroundResource(R.drawable.bg_tag_select);
//                tag.setBackgroundColor(getResources().getColor(R.color.state_bar_color));
                tag.setTextColor(getResources().getColor(R.color.white));
            } else {
                tag.setBackgroundResource(R.drawable.bg_tag_unselect);
//                tag.setBackgroundColor(getResources().getColor(R.color.light_grey));
                tag.setTextColor(getResources().getColor(R.color.black));
            }
        }
    }

    List<Grade> selectGrade;

    class GradeAdapter extends RecyclerArrayAdapter<Grade> {

        public GradeAdapter(Context context) {
            super(context);
        }

        @Override
        public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
            return new GradeViewHolder(parent);
        }
    }

    class GradeViewHolder extends BaseViewHolder<Grade> {

        @BindView(R.id.tag)
        TextView tag;

        public GradeViewHolder(ViewGroup parent) {
            super(parent, R.layout.item_new_dynamic_grade);
            ButterKnife.bind(this, itemView);
        }

        @Override
        public void setData(final Grade data) {
            tag.setText(data.getName());
            setBackGround(data.isSelected());
            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    data.setSelected(!data.isSelected());
                    setBackGround(data.isSelected());
                    if (selectGrade.contains(data)) {
                        selectGrade.remove(data);
                    } else {
                        selectGrade.add(data);
                    }
                }
            });
        }

        private void setBackGround(boolean select) {
            if (select) {
                tag.setBackgroundResource(R.drawable.bg_tag_select);
//                tag.setBackgroundColor(getResources().getColor(R.color.state_bar_color));
                tag.setTextColor(getResources().getColor(R.color.white));
            } else {
                tag.setBackgroundResource(R.drawable.bg_tag_unselect);
//                tag.setBackgroundColor(getResources().getColor(R.color.light_grey));
                tag.setTextColor(getResources().getColor(R.color.black));
            }
        }
    }

    private LoadingDialog _loadingDialog;

    /**
     * 显示加载对话框
     *
     * @param message
     */
    public void showLoadingDialog(String message) {
        if (null != _loadingDialog) {
            return;
        }

        _loadingDialog = new LoadingDialog(this, message);
        _loadingDialog.setCancelable(true);
        _loadingDialog.setCanceledOnTouchOutside(false);
        _loadingDialog.show();
    }

    /**
     * 隐藏登录对话框
     */
    public void hideLoadingDialog() {
        if (null != _loadingDialog && _loadingDialog.isShowing()) {
            _loadingDialog.dismiss();
            _loadingDialog = null;
        }
    }

    protected void showShortToast(String source) {
        Toast.makeText(this, source, Toast.LENGTH_SHORT).show();
    }
}
